﻿using LYR_RPA.dialog;
using LYR_RPA.models.entity;
using LYR_RPA.models.enums;
using LYR_RPA.models.project;
using LYR_RPA.service;
using LYR_RPA.utils;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace LYR_RPA.pages.home
{
    /// <summary>
    /// ProjectPage.xaml 的交互逻辑
    /// </summary>
    public partial class ProjectPage : Page
    {
        private readonly WebSocketClient WebSocketClient;
        private bool flag;
        public ProjectPage()
        {
            InitializeComponent();
            WebSocketClient = WebSocketClient.Instance;
            ObservableCollection<Project> projects = CommonUtils.ReadProject();
            ProjectItems.ItemsSource = projects;
            SearchList.ItemsSource = projects;
            SearchList.DisplayMemberPath = "ScriptName";
        }

        private void Execute_Click(object sender, RoutedEventArgs e)
        {
            
            var button=sender as Button;
            var data= button.DataContext as Project;
            if (flag)
            {
                return;
            }
            flag = true;
            Execute execute = new Execute(){
                Name=data.ScriptName,
                Path=data.Path,
                Msg="正在等待执行",
                IsExecute=false,
                IsCommand=false,
                State= "Orange",
                CreateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            };
            SnackbarThree.Background = Brushes.Green;
            var messageQueue = SnackbarThree.MessageQueue;

            // 显示消息
            var message = "添加执行";
            messageQueue.Enqueue(message);
            Task.Run(() =>
            {
                CommonUtils.AddExecuteTask(execute);
                Click_Valid();
            });
            
        }

        private async void Click_Valid()
        {
            await Task.Delay(3000);
            flag = false;
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            ProjectItems.ItemsSource = CommonUtils.ReadProject();
            string json = JSONUtils.ObjectToString(Result<ObservableCollection<Project>>.ResultContent(ResultEnum.PROJECT, CommonUtils.ReadProject()));
            WebSocketClient.SendMessage(json);
        }

        /*
         * 批量删除
         */
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            var selectItems = ProjectItems.SelectedItems;
            foreach (var idx in Enumerable.Range(0,selectItems.Count))
            {
                var item = selectItems[idx] as Project;

                if (!string.IsNullOrEmpty(item.Path))
                {
                    SQLiteApply.RemoveProject(item);
                }
            }
            CommonUtils.ReadProject();
            CommonUtils.ReadRemoveProject();
        }

        private void Remove_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var data= button.DataContext as Project;
            if (!string.IsNullOrEmpty(data.Path))
            {
                SQLiteApply.RemoveProject(data);
            }
            ProjectItems.ItemsSource = CommonUtils.ReadProject();
        }

        private async void AddTask_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var data = button.DataContext as Project;

            Execute execute = new Execute()
            {
                Name = data.ScriptName,
                Path = data.Path,
                Msg = "正在等待执行",
                IsExecute = false,
                IsCommand = false,
                IsAwait = true,
                IsTask = true,
                State = "Orange",
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                ExecuteTime = DateTime.Now
            };
            TimeDialog timeDialog = new TimeDialog(execute);
            //创建弹窗标题
            Window window = new Window
            {
                Content = timeDialog,
                WindowStyle = WindowStyle.None,
                SizeToContent = SizeToContent.WidthAndHeight,  // 设置为 Manual
                MinHeight = 250,  // 指定宽度
                MinWidth = 300,  // 指定高度
                MaxWidth = 600,
                MaxHeight = 600,
                ShowInTaskbar = false,
                ResizeMode = ResizeMode.NoResize,
                WindowState = WindowState.Normal,
                AllowsTransparency = true,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                Background = Brushes.Transparent,
            };
            //窗口焦点
            window.Activate();
            //置顶
            window.Topmost = true;
            window.ShowDialog();
            SnackbarThree.Background = Brushes.Green;
            var messageQueue = SnackbarThree.MessageQueue;
            
            await Task.Run(() =>
            {
                CommonUtils.AddExecuteTask(execute);
            });
            // 显示消息
            var message = "正在等待定时执行";
            messageQueue.Enqueue(message);
            
        }

        private void AddFolder_Click(object sender, RoutedEventArgs e)
        {
            // 创建目录选择对话框
            using (System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                // 设置对话框的属性
                folderBrowserDialog.Description = "请选择一个目录";
                folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;

                // 显示对话框并检查用户是否点击了确定按钮
                System.Windows.Forms.DialogResult result = folderBrowserDialog.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    // 用户选择了目录，可以获取所选目录的路径
                    string selectedPath = folderBrowserDialog.SelectedPath;
                    SQLiteApply.InsertFolder(new Folder() { IsFolder=1,Path=selectedPath});
                    CommonUtils.ReadProject();
                    SnackbarThree.Background = Brushes.Green;
                    var messageQueue = SnackbarThree.MessageQueue;
                    // 显示消息
                    var message = "添加成功";
                    messageQueue.Enqueue(message);
                }
            }
        }

        private void AddProject_Click(object sender, RoutedEventArgs e)
        {
            // 创建目录选择对话框
            using (System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                // 设置对话框的属性
                folderBrowserDialog.Description = "请选择一个项目";
                folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;

                // 显示对话框并检查用户是否点击了确定按钮
                System.Windows.Forms.DialogResult result = folderBrowserDialog.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    // 用户选择了目录，可以获取所选目录的路径
                    string selectedPath = folderBrowserDialog.SelectedPath;
                    if (string.IsNullOrEmpty(CommonUtils.VerifyProject(selectedPath)))
                    {
                        SnackbarThree.Background = Brushes.Red;
                        var messageQueue = SnackbarThree.MessageQueue;

                        // 显示消息
                        var message = "选择的不是项目";
                        messageQueue.Enqueue(message);
                    }
                    else
                    {
                        SQLiteApply.InsertFolder(new Folder() { IsFolder=0,Path=selectedPath});
                        CommonUtils.ReadProject();
                    }

                }
            }
        }

        private void Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key==Key.Enter) {
                SearchRefresh();
            }
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            SearchRefresh();
        }

        private void SearchRefresh()
        {
            if (string.IsNullOrEmpty(SearchList.Text))
            {
                CommonUtils.ReadProject();
            }
            else
            {
                CommonUtils.SearchProject(SearchList.Text);
            }
        }

        private void SearchComboBox()
        {

        }
    }
}
